import os
import time
from datetime import datetime

import allure
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

def create_path_if_not_exists(path):
    if not os.path.exists(path):
        os.makedirs(path)
        print(f"Created directory at {path}")
    else:
        print(f"Directory already exists at {path}")

def test_get_screen_shot():
    time_stamp = int(time.time())
    # 将时间戳转换为datetime对象
    dt_object = datetime.fromtimestamp(time_stamp)

    # 格式化datetime对象为年-月-日的字符串
    formatted_date1 = dt_object.strftime('%H时-%M分-%S秒')
    print(formatted_date1)
    formatted_date = dt_object.strftime('%Y-%m-%d')
    path = f'./data/img2/{formatted_date}'
    page_path=f'./data/page_source/{formatted_date}'
    file_path = os.path.join(path, f'异常截图-{formatted_date1}.png')
    page_source_path=os.path.join(page_path, f'异常时刻源代码-{formatted_date1}.txt')
    driver = webdriver.Edge()
    driver.get('https://www.baidu.com/')
    try:
        element = driver.find_element(By.LINK_TEXT, '文库12')
        element.click()
    except Exception:
        create_path_if_not_exists(path)
        create_path_if_not_exists(page_path)
        driver.save_screenshot(file_path)
        print('发生异常，已经截图')
        allure.attach.file(file_path,name='异常截图',attachment_type=allure.attachment_type.PNG)
        with open(page_source_path, 'w', encoding='utf-8') as f:
            f.write(driver.page_source)
        allure.attach.file(page_source_path, name='异常时刻源代码', attachment_type=allure.attachment_type.HTML)


if __name__ == '__main__':
    pytest.main(['./web_screen_shot.py','--alluredir=./data/report'])
    #pytest ./web_screen_shot.py --alluredir=./data/report  --clean-alluredir
    #allure serve ./data/report
    # test_get_screen_shot()
